package corp.edu.amadeus.core.bluetooth.sender.impl;

import corp.edu.amadeus.core.bluetooth.sender.ifc.ISender;
import javax.obex.*;
import javax.microedition.io.Connector;
import javax.microedition.io.Connection;
import java.io.OutputStream;
import junit.framework.Assert;
import java.util.Calendar;
import java.util.Date;

public class OBEXSender implements ISender {

	public void send(String url, byte[] content,
			String contentType, String contentName)
			throws Exception {
		//url = "btgoep://001C9A757BB1:9;authenticate=false;encrypt=false;master=false";
		Connection connection = null;
		ClientSession clientSession = null;
		connection = Connector.open(url);
		clientSession = (ClientSession)connection;
		HeaderSet headerC = clientSession.connect(null);
		Assert.assertEquals("CONNECT", ResponseCodes.OBEX_HTTP_OK, headerC.getResponseCode());
		HeaderSet headerSet = clientSession.createHeaderSet();
		headerSet.setHeader(HeaderSet.LENGTH, new Long(content.length));
		headerSet.setHeader(HeaderSet.NAME, contentName);
		headerSet.setHeader(HeaderSet.TYPE, contentType);
		Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        headerSet.setHeader(HeaderSet.TIME_ISO_8601, c);

		/**
		 * NOTE: New message is sent to N80 and E61i when this method is called.
		 * When I send the data below another message arrives.
		 * While only one message is received by SE M600i and Nokia N95.
		 */
		Operation putOperation = clientSession.put(headerSet);
		OutputStream out = putOperation.openOutputStream();
		out.write(content);
		out.flush();
		out.close();
		putOperation.close();
		clientSession.disconnect(null);
		clientSession.close();
	}

}